package com.danke.lib.pay;

import android.content.Intent;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

/**
 * 微信支付回调
 *
 * @author wupuquan
 * @version 1.0
 * @since 2018/12/29 16:09
 */
public class DKPayWXHandler implements IDKPayWXHandler, IWXAPIEventHandler {

    private DKPayActivity activity;
    private IWXAPI wxapi;

    public DKPayWXHandler(DKPayActivity activity, String appId) {
        this.activity = activity;
        this.wxapi = WXAPIFactory.createWXAPI(this.activity.getApplicationContext(), appId);
        wxapi.registerApp(appId);
        wxapi.handleIntent(activity.getIntent(), this);
    }

    @Override
    public void onNewIntent(Intent intent) {
        wxapi.handleIntent(intent, this);
    }

    @Override
    public boolean isWXAppInstalled() {
        return wxapi.isWXAppInstalled();
    }

    @Override
    public int getWXAppSupportAPI() {
        return wxapi.getWXAppSupportAPI();
    }

    @Override
    public void launch(JSONObject credential) {
        try {
            PayReq req = new PayReq();
            req.appId = credential.getString("appId");
            req.partnerId = credential.getString("partnerId");
            req.prepayId = credential.getString("prepayId");
            req.nonceStr = credential.getString("nonceStr");
            req.timeStamp = credential.getString("timeStamp");
            req.packageValue = credential.getString("packageValue");
            req.sign = credential.getString("sign");
            wxapi.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
            activity.setResult(DKPayActivity.FAIL, activity.getString(R.string.DKPay_fail));
        }
    }

    @Override
    public void onReq(BaseReq req) {
        DKPayLog.d("onReq() req= " + req);
    }

    @Override
    public void onResp(BaseResp resp) {
        DKPayLog.d("onResp");
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            DKPayLog.d("DKPayActivity wx result errCode : " + resp.errCode + " , errStr:" + resp.errStr);
            int code = resp.errCode;
            if (code == BaseResp.ErrCode.ERR_OK) {
                activity.setResult(DKPayActivity.SUCCESS);
            } else if (code == BaseResp.ErrCode.ERR_USER_CANCEL) {
                activity.setResult(DKPayActivity.CANCEL, "user_cancelled");
            } else {
                activity.setResult(DKPayActivity.FAIL, activity.getString(R.string.DKPay_fail), "wx_err_code:" + code + "，errStr:" + resp.errStr);
            }
        }
    }

}
